﻿using Fur;
using Fur.Authorization;
using Fur.Core;
using Fur.DatabaseAccessor;
using Fur.LinqBuilder;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace China.Core.JWT
{
    /// <summary>
    /// Auth2.0, identityServer4
    /// </summary>
    public class JwtHandler : AppAuthorizeHandler
    {
        //private readonly IRepository<User> _repository;
        //public JwtHandler(IRepository<User> repository)
        //{
        //    _repository = repository;
        //}

        public override bool Pipeline(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
        {
            // 判断是否传入了token
            var authorizationValue = httpContext.HttpContext.Request.Headers["Authorization"].ToString();
            if (string.IsNullOrEmpty(authorizationValue)) return false;

            // 解析请求报文头的token
            var token = authorizationValue[7..];

            var result = JWTEncryption.Validate(token, App.GetOptions<JWTSettingsOptions>());
            if (!result.IsValid) return false;

            var userId = result.Token.GetPayloadValue<int>("UserId");


            var securityDefine = httpContext.GetEndpoint().Metadata.GetMetadata<SecurityDefineAttribute>();
            if (securityDefine == null) return true;

            // 判断用户的角色拥有那些权限
            var securiteis = Db.GetRepository<User>()
                .Include(u => u.Roles)
                    .ThenInclude(u => u.Securities)
                .Where(u => u.Id == userId)
                .SelectMany(u => u.Roles.SelectMany(u => u.Securities))
                .Select(u => u.UniqueId);

            if (!securiteis.Contains(securityDefine.ResourceId)) return false;

            return true;
        }
    }
}
